<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const user = {
  telphone: proxy.$telPhone
}
// ----
const ewm = reactive({
  add: true,
  maxnum: 1,
  forFree: 1,
  setTrueStyle: {},
  imgs: [],
  option: {
    viewMode: 0,
    dragMode: 'move',
    aspectRatio: 1,
    autoCropArea: 1,
    center: false,
    cropBoxMovable: false,
    cropBoxResizable: false,
    toggleDragModeOnDblclick: false
  },
  cropImg: proxy.$Global.cropImg
})
const advs = reactive({
  add: true,
  maxnum: 0,
  forFree: 1,
  setTrueStyle: {},
  imgs: [],
  option: {
    viewMode: 0,
    dragMode: 'move',
    autoCropArea: 1,
    center: false,
    cropBoxMovable: false,
    cropBoxResizable: false,
    toggleDragModeOnDblclick: false
  },
  cropImg: proxy.$Global.cropImg
})
// ----
let globalData = {}
const isMobile = /^(1[3456789]\d{9})$/
// ----
let forSortNum = 0
// ----
const form = reactive({
  name: '',
  desc: '',
  leader: '',
  telphone: ''
})

/* ---- */
const uploadoss = ref()
const layer = ref()
const layerBox = ref()
const layerLoading = ref()

/* ---- */
const getFormInfo = async () => {
  advs.setTrueStyle = { height: `${document.querySelector('.squareBox dl dd label').clientWidth / advs.forFree}px` }
  ewm.setTrueStyle = { height: `${document.querySelector('.powerBox dl dd label').clientWidth / ewm.forFree}px` }
  // ----
  if (proxy.$route.query.id) {
    await proxy.$http.get('meeting-organiser/index', {
      params: { 'MeetingOrganiserSearch[id]': proxy.$route.query.id }
    }).then((res) => {
      const PData = res.items[0] || {}
      // ----
      form.name = PData.name
      form.leader = PData.delegate
      form.telphone = PData.telphone
      // ----
      proxy.$Myfun.getJsonData(PData.remark, (resJson) => {
        const RJData = resJson[0] || {}
        globalData = RJData
        // ----
        if (RJData.desc) form.desc = resJson[0].desc
      })
      // ----
      proxy.$Myfun.getJsonData(PData.ads_image, (resJson) => {
        resJson.forEach((item) => {
          advs.imgs.push({
            imgName: item.name,
            imgUrl: item.image,
            imgW: item.width,
            imgH: item.height
          })
        })
        if (Number(advs.imgs.length) >= Number(advs.maxnum) && Number(advs.maxnum) > 0) advs.add = !advs.add
      })
      // ----
      proxy.$Myfun.getJsonData(PData.qrcode_image, (resJson) => {
        resJson.forEach((item) => {
          ewm.imgs.push({
            imgName: item.name,
            imgUrl: item.image,
            imgW: item.width,
            imgH: item.height
          })
        })
        if (Number(ewm.imgs.length) >= Number(ewm.maxnum) && Number(ewm.maxnum) > 0) ewm.add = !ewm.add
      })
    }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  }
}
// --上传图片操作--
const uploadAct = (type, selectObj, event, index) => {
  const uploadOss = uploadoss.value
  switch (Number(type)) {
    case 1: {
      uploadOss.uploadImg(event, selectObj,'imgs', index)
      break
    }
    case 2: {
      uploadOss.delInfo(selectObj, event)
      break
    }
    case 3: {
      uploadOss.uploadImgMoreWX(selectObj)
      break
    }
  }
}
// ----
const emptyInfo = (event) => {
  const curEL = event.currentTarget
  const input = curEL.parentElement.querySelector('input')
  input.value = ''
  input.dispatchEvent(new Event('input'))
}
// ----
const subform = async () => {
  if (Number(form.name.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写名称标题！')
    return false
  }
  if (Number(form.desc.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写业务描述！')
    return false
  }
  if (!isMobile.test(form.telphone)) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写合法的手机号！')
    return false
  }
  // --获取排序--
  if (!proxy.$route.query.id) {
    const forSortData = {
      params: {
        sort: 'SORT_DESC',
        // ----
        page: 1,
        PageSize: 1
      }
    }
    await proxy.$Axios.all([
      proxy.$Axios.get('meeting-organiser/index', forSortData)
    ]).then(proxy.$Axios.spread((sortData) => {
      if (Number(sortData.items.length) > 0) forSortNum = sortData.items[0].sort_num
    })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  }
  // ----
  globalData.desc = form.desc
  // ----
  const forRemark = JSON.stringify(globalData)
  // ----
  let forAdvs = ''
  if (Number(advs.imgs.length) > 0) {
    const advsItems = []
    advs.imgs.forEach((item) => {
      advsItems.push({
        name: item.imgName,
        image: item.imgUrl,
        width: item.imgW,
        height: item.imgH
      })
    })
    forAdvs = JSON.stringify(advsItems)
  }
  // ----
  let forEwm = ''
  if (Number(ewm.imgs.length) > 0) {
    const ewmItems = []
    ewm.imgs.forEach((item) => {
      ewmItems.push({
        name: item.imgName,
        image: item.imgUrl,
        width: item.imgW,
        height: item.imgH
      })
    })
    forEwm = JSON.stringify(ewmItems)
  }
  // ----
  let forType = 'post'
  let forUrl = 'meeting-organiser/create'
  let forData = {
    dealer_id: logUser.id,
    meeting_id: 2,
    // ----
    sort_num: Number(forSortNum + 1),
    // ----
    name: form.name,
    delegate: form.leader,
    telphone: form.telphone,
    ads_image: forAdvs,
    qrcode_image: forEwm,
    remark: forRemark,
    // ----
    config_id: userInfo.config_id,
    openid: userInfo.openid
  }
  if (proxy.$route.query.id) {
    forType = 'patch'
    forUrl = 'meeting-organiser/update?id=' + proxy.$route.query.id
    forData = {
      status: 0,
      // ----
      name: form.name,
      delegate: form.leader,
      telphone: form.telphone,
      ads_image: forAdvs,
      qrcode_image: forEwm,
      remark: forRemark,
      // ----
      config_id: userInfo.config_id,
      openid: userInfo.openid
    }
  }
  // ----
  proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
  let resData = ''
  await proxy.$http[forType](forUrl, forData).then((res) => { resData = res }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  proxy.$Myfun.disLoading(layerLoading.value, 'close')
  if (resData) {
    const forOptions = {
      shadeClose: false,
      title: '推广信息提交成功',
      content: '等待审核',
      button: [{
        text: proxy.$Global.layer.btnCancel,
        callback: () => {
          layerBox.value.close()
          // ----
          proxy.$router.back()
        }
      }, {
        text: proxy.$Global.layer.btnAsk,
        class: 'xw-color-24',
        callback: () => { window.location.href = 'tel:' + user.telphone }
      }]
    }
    proxy.$Myfun.isIndepth(layerBox.value, 'open', forOptions)
  }
}
const goback = () => { proxy.$router.back() }

/* ---- */
onMounted(() => {
  getFormInfo()
})
onBeforeRouteLeave(() => { proxy.$Myfun.setScrollTop(proxy.$refs.formSection) })
</script>

<template>
  <div class="mescroll-touch" ref="formSection">
    <div class="formSet">
      <ul>
        <li>
          <div class="form-are xw-radius-3">
            <h1>名称标题</h1>
            <p><textarea class="tarea-H2" placeholder="" v-model.trim="form.name"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-are xw-radius-3">
            <h1>业务描述</h1>
            <p><textarea class="tarea-H2" placeholder="" v-model.trim="form.desc"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>业务负责</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model.trim="form.leader"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.leader"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>手机号码</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model.trim="form.telphone"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.telphone"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-imgs xw-radius-3 powerBox">
            <div class="FIS-top xw-flex xw-flex-align xw-flex-justify">
              <span class="FIS-title">微信二维码</span>
            </div>
            <dl class="FIS-img">
              <dd v-for="(item, index) in ewm.imgs"><label class="xw-block xw-act"><img :src="item.imgUrl"/><input type="file" style="display: none;" accept="image/*" @change="uploadAct(1, ewm, $event, index)"/></label><span class="FIS-del fal fa-times xw-act" @click="uploadAct(2, ewm, index)"></span></dd>
              <dd v-if="ewm.add"><label class="xw-act xw-flex xw-flex-center" :style="ewm.setTrueStyle"><em class="fal fa-plus"></em><input type="file" style="display: none;" accept="image/*" @change="uploadAct(1, ewm, $event)"/></label></dd>
            </dl>
          </div>
        </li>
        <li>
          <div class="form-imgs xw-radius-3 squareBox">
            <div class="FIS-top xw-flex xw-flex-align xw-flex-justify">
              <span class="FIS-title">图片说明</span>
              <span v-if="Number(advs.maxnum) > 0">数量：最多{{advs.maxnum}}张</span>
            </div>
            <dl class="FIS-img xw-float">
              <dd class="xw-float-W3" v-for="(item, index) in advs.imgs"><label class="xw-block xw-act" :style="advs.setTrueStyle"><div class="xw-bgImg" :style="{ backgroundImage: 'url(' + item.imgUrl + ')' }"></div><input type="file" style="display: none;" accept="image/*" @change="uploadAct(1, advs, $event, index)"/></label><span class="FIS-del fal fa-times xw-act" @click="uploadAct(2, advs, index)"></span></dd>
              <dd class="xw-float-W3" v-if="advs.add"><label class="xw-act xw-flex xw-flex-center" :style="advs.setTrueStyle" @click="uploadAct(3, advs)"><em class="fal fa-plus"></em></label></dd>
            </dl>
          </div>
        </li>
      </ul>
      <div class="form-sub xw-radius-3 xw-bgCL-11 xw-act" @click="subform">确定提交</div>
      <div class="form-sub xw-radius-3 xw-WhiteRed xw-act" @click="goback">取消返回</div>
    </div>
    <uploadoss-view ref="uploadoss"/>
    <layer-view ref="layer"/>
    <layer-view ref="layerBox"/>
    <layer-view ref="layerLoading"/>
  </div>
</template>